package org.example.handle.baidu;

import com.baidu.aip.ocr.AipOcr;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.example.constant.OcrItem;
import org.example.handle.AbstractHandle;
import org.example.handle.AuthToken;
import org.example.http.SimpleHeader;
import org.example.ini.BaiduIniProperty;
import org.example.ini.IniReader;
import org.example.util.JsonUtil;
import org.json.JSONArray;
import org.json.JSONObject;

import java.awt.image.BufferedImage;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.StringJoiner;

public class BaiduOcrHandle extends AbstractHandle {

    private static final String GENERAL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic";
    private static final String AUTH_TOKEN = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s";

    private final BaiduIniProperty property = IniReader.read(System.getProperty("user.dir") + "/config/cfg.ini", OcrItem.BAIDU, BaiduIniProperty.class);

    private final AuthToken accessToken = new AuthToken();

    @Override
    public Object generalTemp(BufferedImage image) {
        //判断token是否存在或者过期
        if (!accessToken.hasValidToken()) {
            // 重新获取token
            this.auth();
        }

        AipOcr aipOcr = new AipOcr(property.getAppId(), property.getApiKey(), property.getSecretKey());
        byte[] imageBytes = bufferedImageToByte(image, "png");
        JSONObject jsonObject = aipOcr.basicGeneral(imageBytes, new HashMap<>());
        if (null == jsonObject) return "";
        JSONArray wordsResult = jsonObject.getJSONArray("words_result");
        if (null == wordsResult || wordsResult.length() == 0) return "";
        StringJoiner sj = new StringJoiner("\r\n");
        for (int i = 0; i < wordsResult.length(); i++) {
            sj.add(wordsResult.getJSONObject(i).getString("words"));
        }
        return sj.toString();
    }

    private AuthToken auth() {
        String response = doGet(String.format(AUTH_TOKEN, property.getApiKey(), property.getSecretKey()));
        BaiduAuthTokenResponse tokenResponse = JsonUtil.toJavaObject(response, BaiduAuthTokenResponse.class);
        accessToken.setExpireAt(System.currentTimeMillis() / 1000 + tokenResponse.getExpiresIn());
        accessToken.setAccessToken(tokenResponse.getAccessToken());
        return accessToken;
    }

    /**
     * 组装http请求头
     */
    private Map<String, String> buildHttpHeader() {
        String curTime = System.currentTimeMillis() / 1000L + "";
        String param = "{\"engine_type\":\"recognize_document\"}";
        String paramBase64 = new String(Base64.encodeBase64(param.getBytes(StandardCharsets.UTF_8)));
        String checkSum = DigestUtils.md5Hex(property.getApiKey() + curTime + paramBase64);
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
        header.put("X-Param", paramBase64);
        header.put("X-CurTime", curTime);
        header.put("X-CheckSum", checkSum);
        header.put("X-Appid", property.getAppId());
        return header;
    }
}
